/*
 * VERSION: 1.0
 * OWNER  : kr.goodwilldd@gmail.com
 * 
 * 
 */
;(function($) {
	var fullScreenWidth = screen.availWidth-20;
	var fullScreenHeight = screen.availHeight;
	var defaultParam = {
			zoom:1,
			images: [],
			targetDiv: 'mainZone',
			maxWidth : 1000,
			maxHeight: 800,
			control : {
				turnLeft:{show : true, text :'TurnLeft'},
				turnRight:{show : true, text :'turnRight'},
				turnReverse:{show : true, text :'turnReverse'},
				fullWidth:{show : true, text :'fullWidth'},
				fullHeight:{show : true, text :'fullHeight'},
				fullImage:{show : true, text :'fullImage'},
				zoomIn : {show : true, level : 2, text :'zoomIn'},
				zoomOut : {show : true, level : -2, text :'zoomOut'},
				print : {show : true, text :'print'},
				fullScreen : {show : true, text :'fullScreen'}
			}
	};
	var controlDiv = "<div id='controlZone'></div>";
	var thumbnailDiv = "<div id='thumbnailZone'></div>";
	var mainDiv = "<div id='mainZone'></div>";
	var agt = navigator.userAgent.toLowerCase();
	function makeBtn(param){
		// param = { id : id , text : text, cls : class};
		var btn = "<button ";
		if ( param.id != null && param.id != 'undefined')
			btn+="id='"+param.id+"'";
		if ( param.cls != null && param.cls != 'undefined')
			btn+="class='"+param.cls+"'";
		btn+=">";
		if ( param.text != null && param.text != 'undefined')
			btn+=param.text+"</button>";
		return btn;
	};
	function debug(message) {
		if (window.console && window.console.log) {
			window.console.log(message);
		}
	};
	function makeImg(src, alt, cls) {
		var img = "<img src='"+src+"' ";
		if ( alt != '' )
			img += "alt='"+alt+"' ";
		
		if ( cls != '' )
			img += "class='"+cls+"'";
		img+="/><br />";
		return img;
	}
	
	$.fn.ImageResize = function( params ) {

		var aspectRatio = 0;
		if ( !params.height && !params.width ) {
			return this;
		}
		if ( params.height && params.width ) {
			aspectRatio = params.width / params.height;
		}
		return this.one( "load", function() {
			this.removeAttribute( "height" );
			this.removeAttribute( "width" );
			this.style.height = this.style.width = "";

			var imgHeight = this.height
				, imgWidth = this.width
				, imgAspectRatio = imgWidth / imgHeight
				, bxHeight = params.height
				, bxWidth = params.width
				, bxAspectRatio = aspectRatio;
			if ( !bxAspectRatio ) {
				if ( bxHeight ) {
					bxAspectRatio = imgAspectRatio + 1;
				} else {
					bxAspectRatio = imgAspectRatio - 1;
				}
			}
			if ( (bxHeight && imgHeight > bxHeight) || (bxWidth && imgWidth > bxWidth) ) {

				if ( imgAspectRatio > bxAspectRatio ) {
					bxHeight = ~~ ( imgHeight / imgWidth * bxWidth );
				} else {
					bxWidth = ~~ ( imgWidth / imgHeight * bxHeight );
				}

				this.height = bxHeight;
				this.width = bxWidth;
			}
		})
		.each(function() {
			if ( this.complete ) {
				$( this ).trigger( "load" );
			}
			this.src = this.src;
		});
	};
	
	$.fn.replaceMainZone = function(param) {
		var mainZoneParam = {
				width:500,
				height: 750
		};
		$.extend(true, mainZoneParam, param);
		var mdiv = $("#"+defaultParam.targetDiv);
		var p = mdiv.parent();
		mdiv.remove();
		p.append(mainDiv);
		$("#"+defaultParam.targetDiv).append(makeImg(this.attr("src"),'','mainZoneImg'));
		($("#"+defaultParam.targetDiv).find("img")).ImageResize({ height: mainZoneParam.height, width: mainZoneParam.width });
	};
	
	$.fn.thumbnailCaption = function() {
		this.css({margin:'10px 0 0 10px', position:'relative', width: '300px'});
		this.find("img").each(function(){
			var imageCaption = $(this).attr("alt");
			$(this).load(function() {
				if (imageCaption != '') {
		            var imgWidth = $(this).width();
		            var imgHeight = $(this).height();
		            var position = $(this).position();
		            var positionTop = (position.top + imgHeight - 26);
		            $("<span style='background-color:#F00;text-align:center;height:26px;line-height:26px;display:block;'><em style='display:block;'>"+imageCaption+"</em></span>")
		            .css({"position":"absolute", "top":positionTop+"px", "left":"0", "width":imgWidth +"px"})
		            .insertAfter(this);
		        }			
			});
			$(this).click(function() {
				$(this).replaceMainZone();
			});
		});
	};
	
	$.fn.zoom = function(param) {
		defaultParam.zoom += (param.zoom/10);
		this.animate({opacity:"1", zoom: (defaultParam.zoom*100)+"%"}, 150, function(){});
	};
	
	jQuery.fn.extend({
		setInit:function(param) {
			$.extend(true, defaultParam, param);
			this.append(controlDiv);
			this.append(thumbnailDiv);
			this.append(mainDiv);
			var cdiv = $("#controlZone");
			var tdiv = $("#thumbnailZone");
			
			// 썸네일 생성
			var imageCount = 0;
			$.each(defaultParam.images, function(key, value){
				imageCount++;
				var caption = imageCount+" / "+defaultParam.images.length;
				tdiv.append(makeImg(value, caption, 'thumbnail'));
			});
			
			// caption 등록
			tdiv.thumbnailCaption();
			// 메인 이미지 설정
			tdiv.find("img:first").replaceMainZone();
			var angle = 0;
			// 컨트롤 생성
			$.each(defaultParam.control, function(key, value) {
				if ( value.show ) {
					cdiv.append(makeBtn({id:key,text:value.text}));
					switch(key) {
					case 'turnLeft':
						$("#turnLeft").click(function() {
							angle+=90;
							//$("#"+defaultParam.targetDiv).find("img").rotate({animateTo:(angle+=90)});
							$(".mainZoneImg").rotate({animateTo:angle});
						});
						break;
					case 'turnRight':
						$("#turnRight").click(function() {
							angle-=90;
							//$("#"+defaultParam.targetDiv).find("img").rotate({animateTo:angle});
							$(".mainZoneImg").rotate({animateTo:angle});
						});
						break;
					case 'turnReverse':
						$("#turnReverse").click(function() {
							angle+=180;
							//$("#"+defaultParam.targetDiv).find("img").rotate({animateTo:angle});
							$(".mainZoneImg").rotate({animateTo:angle});
						});
						break;
					case 'fullWidth':
						// 가로는 좀 고민해봐야할듯;
						$("#fullWidth").click(function(){
							tdiv.find("img:first").replaceMainZone({
								width : 1200,
								height: 1200
							});
							angle = 0;
						});
						break;
					case 'fullHeight':
						$("#fullHeight").click(function(){
							tdiv.find("img:first").replaceMainZone({
								width : 'auto',
								height: defaultParam.maxHeight
							});
							angle = 0;
						});
						break;
					case 'fullImage':
						$("#fullImage").click(function(){
							tdiv.find("img:first").replaceMainZone({
								width : 0,
								height: 0
							});
							$(".mainZoneImg").removeAttr("width");
							$(".mainZoneImg").removeAttr("height");
							$(".mainZoneImg").removeAttr("style");
							angle = 0;
						});
						break;
					case 'print':
						$("#print").click(function(){
							$("#"+defaultParam.targetDiv).printThis({
								debug:false,
								importCSS: false,
								printContainer:true,
								loadCSS:"",
								pageTitle:"제목",
								removeInline: false
							});
						});
						break;
					case 'fullScreen':
						$("#fullScreen").click(function(){
							var fullScreenWin = window.open($("#"+defaultParam.targetDiv).find("img").attr("src"), "fullScreenWin","width="+fullScreenWidth+",height="+fullScreenHeight+",scrollbars,top=0,left=0");
							$(fullScreenWin).keydown(function(event){
								if ( event.which == 27 ) {//esc
									fullScreenWin.close();
								}
							});
						});
						break;
					case 'zoomIn':
						$("#zoomIn").click(function(){
							$("#"+defaultParam.targetDiv).find("img").zoom({zoom : 2});
						});
						break;
					case 'zoomOut':
						$("#zoomOut").click(function(){
							$("#"+defaultParam.targetDiv).find("img").zoom({zoom : -2});
						});
						break;
					default:
						return;
					}
				}
			});
		}
	});
})(jQuery);

/* 실제 이미지 사이즈 */
;(function($){
    var
    props = ['Width', 'Height'],
    prop;

    while (prop = props.pop()) {
    (function (natural, prop) {
      $.fn[natural] = (natural in new Image()) ? 
      function () {
      return this[0][natural];
      } : 
      function () {
      var 
      node = this[0],
      img,
      value;

      if (node.tagName.toLowerCase() === 'img') {
        img = new Image();
        img.src = node.src,
        value = img[prop];
      }
      return value;
      };
    }('natural' + prop, prop.toLowerCase()));
    }
  }(jQuery));